#订单页面
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views.generic import View
from apps.home_page.models import *
from django_redis import get_redis_connection
import datetime
from django.db import transaction
from django.core.paginator import Paginator
from django.db.models import Q

class Udai_order(View):
    def get(self, request):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=user_id)
            orders = UdwOrder.objects.filter(user_id=user_id)   #当前用户所有订单
            unpaid_num = 0  #未付款
            unpaid_orders = []
            unshipment_num =0 #待发货
            unshipment_orders = []
            unreceiving_num = 0  #待收货
            unreceiving_orders = []
            unevaluate_num = 0 #待评价
            unevaluate_orders = []
            for order in orders:
                # 待评价
                if order.status == '6':
                    unevaluate_num += 1
                    goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)  # 商品详细信息
                    goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id).goods_name  # 商品goods表
                    goods_dict = {}
                    b = {goods_name: goods_info}
                    goods_dict[order] = b
                    unevaluate_orders.append(goods_dict)
                #未付款
                elif order.pay_status == '0':
                    unpaid_num += 1
                    goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)  # 商品详细信息
                    goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id).goods_name
                    goods_dict = {}
                    b = {goods_name: goods_info}
                    goods_dict[order] = b
                    unpaid_orders.append(goods_dict)


                #待发货
                elif order.distribution_status == '0':
                    unshipment_num +=1
                    goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id) #商品详细信息
                    goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id).goods_name   #商品goods表
                    goods_dict = {}
                    b = {goods_name:goods_info}
                    goods_dict[order] = b
                    unshipment_orders.append(goods_dict)
                # 待收货
                elif order.distribution_status == '1':
                    unreceiving_num += 1
                    goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)  # 商品详细信息
                    goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id).goods_name  # 商品goods表
                    goods_dict = {}
                    b = {goods_name: goods_info}
                    goods_dict[order] = b
                    unreceiving_orders.append(goods_dict)


            print(unevaluate_orders)
            con = {
                'username': user.user_phone,
                'unpaid_num': unpaid_num,   #未付款商品数量
                'unpaid_orders': unpaid_orders,   #未付款商品订单详情及商品详细信息
                'unshipment_num' :unshipment_num,   #待发货的商品数量
                'unshipment_orders' :unshipment_orders,#待发货的商品订单详情及商品详细信息
                'unreceiving_num':unreceiving_num, #待收货的数量
                'unreceiving_orders':unreceiving_orders,#待收货的商品订单详情及商品详细信息
                'unevaluate_num':unevaluate_num,   #待评价的数量
                'unevaluate_orders':unevaluate_orders,#待评价的商品订单详情及商品详细信息
            }
            return render(request, 'udai_order.html', context=con)

    def post(self, request):
        pass

#我的收藏
class Udai_collection(View):
    def get(self, request, pindex):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=user_id)
            username = user.user_phone
            goods = []
            favs = UdwFavorite.objects.filter(user_id=user.user_id)  #当前用户的所有的收藏
            for f in favs:
                g = UdwGoods.objects.get(goods_id=f.goods_id)
                goods.append(g)
            paginator = Paginator(goods, 2)
            if pindex == '':
                pindex = 1
            else:
                int(pindex)
            page = paginator.page(pindex)

        context = {
            'username':username,
            'page':page,
        }
        return render(request, 'udai_collection.html', context)

    def post(self, request, pindex):
        pass

#立即收藏
def collection_goods(request, id):
    user_id = request.session.get('id')
    if not user_id:
        return redirect('login_register:login')
    else:
        user_fas = UdwFavorite.objects.filter(Q(user_id=user_id)&Q(goods_id=id))
        print(user_fas)
        if not user_fas:
            UdwFavorite.objects.create(user_id=user_id, goods_id=id,
                                       time=datetime.datetime.now())
            return HttpResponse('收藏成功')
        else:
            return HttpResponse('已经存在')

#取消收藏接口
def delete_collection(request, id):
    user_id = request.session.get('id')
    try:
        UdwFavorite.objects.get(Q(goods_id=id)&Q(user_id=user_id)).delete()
    except UdwFavorite.DoesNotExist:
        pass

    return HttpResponse('取消收藏成功')

#订单支付页面
class Pay_page(View):
    def get(self, request, id):
        #获取当前用户
        user1 = request.session.get('id')
        if not user1:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=user1)
            username = user.user_phone
            #当前用户提交的订单号 查找出当前的订单信息
            order_user_info = UdwOrder.objects.get(order_id=id)
            #通过order表找到用户提交的订单地址
            order_user_site = None
            try:
                order_user_site = UdwUserSite.objects.get(site_id=order_user_info.site_id)
            except UdwUserSite.DoesNotExist:
                pass
            order_all_site = UdwUserSite.objects.filter(user_id=order_user_info.user_id)
            #订单详细信息
            good_info = UdwGoodsInfo.objects.get(goods_info_id=order_user_info.goods_info_id)
            #当前商品的名字
            good = UdwGoods.objects.get(goods_id=good_info.goods_id)
            context = {
                'user': user,
                'username':username,
                'order':order_user_info,  #当前订单用户的信息
                'de_site':order_user_site,  #当前订单用户的地址信息
                'sites':order_all_site,   #当前用户的所有地址
                'good':good,
                'good_info':good_info,

            }
            return  render(request, 'pay_page.html', context)
    def post(self, request, id):
        # 提交订单
        pay_mode = request.POST.get('pay-mode')
        pay_site = request.POST.get('addr')
        if not all([pay_mode, pay_site]):
            return HttpResponse('提交数据不完整')
        else:
            oder = UdwOrder.objects.get(order_id=id)
            user_id = request.session.get('id')
            user_info = UdwUser.objects.get(user_id=user_id)

            if pay_mode == '1':
                #获取当前商品的实付价钱
                payable_amount = oder.payable_amount
                print('师傅价钱%d'%payable_amount)
                #当前用户的余额
                if user_info.user_integral >= payable_amount:
                    user_info.user_integral -= payable_amount
                    user_info.save()
                    #订单信息变动
                    oder.pay_code = user_info.user_phone
                    oder.status = '2'
                    oder.pay_status = '1'
                    oder.real_amount = payable_amount
                    oder.pay_time = datetime.datetime.now()
                    oder.site_id = pay_site
                    oder.distribution_status = '0'
                    oder.save()
                    #用户余额变动表
                    UdwUserMoney.objects.create(
                        user_id=user_id,
                        money_source='1',
                        money_amount=payable_amount,
                        create_time=datetime.datetime.now()
                    )
                    return HttpResponse('支付成功')
                else:
                    return HttpResponse('余额不足')
            elif pay_mode == '2':
                return HttpResponse('此功能正在开发')
            elif pay_mode == '3':
                return HttpResponse('此功能正在开发')
            else:
                return HttpResponse('选错了')

#订单等待收货接口
class Udai_order_wait_receipted(View):
    def get(self, request, id):
        pass
    def post(self, request, id):
        pass



#订单确认收货接口
class Udai_order_receipted(View):
    def get(self, request, id):
        print('传过来的%s'%id)
        user1 = request.session.get('id')
        if not user1:
            return redirect('login_register:login')
        else:
            user = UdwUser.objects.get(user_id=user1)  #当前用户的信息
            order = UdwOrder.objects.get(order_id=id)  #当前用的订单信息
            goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id) #当前商品的尺码信息
            goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id)  #当前商品的名字信息
            orders = []
            oders_info = {}
            b = {goods_name:goods_info}
            oders_info[order] = b
            orders.append(oders_info)
            #用户的收货地址
            user_site = UdwUserSite.objects.get(site_id=user.user_id)

            context = {
                'user':user,
                'order':order,
                'orders':orders,
                'user_site':user_site,
            }
        return render(request, 'udai_order_receipted.html', context)
    def post(self, request, id):
        pwd = request.POST.get('pwd')
        user_id = request.session.get('id')
        user = UdwUser.objects.get(user_id=user_id)
        order = UdwOrder.objects.get(order_id=id)
        #物品应增加积分
        good_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id).goods_info_intergral
        if pwd == user.payment_code:
            order.status = '6'
            order.pay_status = '1'
            order.distribution_status = '1'
            order.completion_time = datetime.datetime.now()
            order.point = good_info
            order.exp = 5
            order.save()
            #获取当前用户的积分值
            user.user_integral += good_info
            user.save()
            return HttpResponse('确认收货成功')
        else:
            return HttpResponse('支付密码错误')

#退货退款接口
class Udai_apply_return(View):
    def get(self, request, id):
        user_id = request.session.get('id')
        if not user_id:
            return render(request, 'login.html')
        else:
            user = UdwUser.objects.get(user_id=user_id)  #查找出当前用户的信息
            order = UdwOrder.objects.get(order_id=id)  # 当前用的订单信息
            goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)  # 当前商品的尺码信息
            goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id)  # 当前商品的名字信息
            goods_real_money = order.real_amount   #当前商品的实付价钱
            orders = []
            oders_info = {}
            b = {goods_name: goods_info}
            oders_info[order] = b
            orders.append(oders_info)
        context = {
            'user':user,
            'order':order,
            'orders':orders,
            'goods_real_money':goods_real_money
        }
        return render(request, 'udai_apply_return.html',context)
    def post(self, request, id):
        user_id = request.session.get('id')  #获取当前的用户
        user = UdwUser.objects.get(user_id=user_id)  #获取用户的信息
        order = UdwOrder.objects.get(order_id=id)   #获取当前用户的订单信息
        money = request.POST.get('money')
        item = request.POST.get('item')
        option = request.POST.get('option')
        order_real_money = order.real_amount  #当前订单实付价钱（没有写运费功能）
        if (money == '0')& (item == '0'):#俩者都为0时仅退款
                #退还给当前用户钱 更改订单表  更改退款表
                user.user_integral +=order_real_money
                user.save()
                order.pay_status = '2'
                order.save()
                UdwSalesReturn.objects.create(
                    return_no=order.order_id, #订单编号
                    user_id=user.user_id, #当前用户id
                    order_id=order.order_id, #订单ID
                    return_time=datetime.datetime.now(),
                    return_status='2',
                    return_operation='1',
                )
                return HttpResponse('仅退款成功')
        elif (money == '1')&( item == '1'): #为1是已收到货 应联系商家退回货物
                order.pay_status = '2'
                order.save()
                UdwSalesReturn.objects.create(
                    return_no=order.order_id,  # 订单编号
                    user_id=user.user_id,  # 当前用户id
                    order_id=order.order_id,  # 订单ID
                    return_time=datetime.datetime.now(),
                    return_status='0',
                    return_operation='0',
                )
                return HttpResponse('等待退回货物')
        else:
            return HttpResponse('输入有误，请选择正确的退款流程')

#取消订单
def delete_order(request, id):
    user_id = request.session.get('id')  # 获取当前的用户
    user = UdwUser.objects.get(user_id=user_id)  # 获取用户的信息
    order = UdwOrder.objects.get(order_id=id)  # 获取当前用户的订单信息
    goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)  #商品的信息
    order.status = '3'
    order.save()
    goods_info.goods_info_num += order.goods_number
    goods_info.save()
    return HttpResponse('取消订单成功')

#退款/退货页面显示
class Udai_show_refund(View):
    def get(self, request):
        user_id = request.session.get('id')
        print(1)
        print(user_id)
        if not user_id:
            print(2)
            return redirect('login_register:login')

        else:
            user = UdwUser.objects.get(user_id=user_id)
            sales_returns = UdwSalesReturn.objects.filter(user_id=user.user_id)
            return_money_num = 0
            return_money_num_list = []
            return_googs = 0
            return_googs_list = []
            order_list = []
            order_list2 = []
            order_list3 = []
            for sales_return in sales_returns:
                order_dic = {}
                order = UdwOrder.objects.get(order_id=sales_return.order_id)
                goods_info = UdwGoodsInfo.objects.get(goods_info_id=order.goods_info_id)
                goods_name = UdwGoods.objects.get(goods_id=goods_info.goods_id)
                #所以订单的
                b = {goods_name: goods_info}
                order_dic[order] = b
                order_list.append(order_dic)
                if sales_return.return_status == '2':
                    return_money_num +=1
                    return_money_num_list.append(sales_return)
                    b = {goods_name: goods_info}
                    order_dic[order] = b
                    order_list2.append(order_dic)
                    # print('order_list2%s'%order_list2)

                elif sales_return.return_status=='0':
                    return_googs +=1
                    return_googs_list.append(sales_return)
                    b = {goods_name: goods_info}
                    order_dic[order] = b
                    order_list3.append(order_dic)
                    # print('order_list3%s' % order_list3)
                else:
                    pass

            con = {
                'username': user.user_phone,
                'return_money_num':return_money_num,
                'return_googs':return_googs,
                'orders_list':order_list,
                'orders_list2':order_list2,
                'orders_list3': order_list3,
            }

            return render(request, 'udai_refund.html', context=con)
    def post(self, request):
        pass




















